package com.hx.voice.recognition.auth.server.controller;

import com.hx.voice.recognition.auth.server.service.IAuthClientService;
import com.hx.voice.recognition.auth.server.util.user.JwtAuthenticationRequest;
import com.hx.zjb.security.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @descripe：登录授权controller
 * @company：南京华讯方舟通讯设备有限公司
 * @author：zhoujinbing
 * @time：2019/6/14 15:05
 * @version：V1.0
 */
@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {

    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    public IAuthClientService authClientService;

    /**
     * @description 根据用户名密码生成token
     * @method  createAuthenticationToken
     * @param  [authenticationRequest]
     * @return com.hx.zjb.security.common.msg.ObjectRestResponse<java.lang.String>
     * @date: 2019/6/18 14:39
     * @author:zhoujinbing
     */
    @RequestMapping(value = "/token",method = RequestMethod.POST)
    public ObjectRestResponse<String> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
        log.info("{} request login",authenticationRequest.getUsername());
        final String token = authClientService.login(authenticationRequest);
        log.info("{} generate token is {}",authenticationRequest.getUsername(),token);
        return new ObjectRestResponse<String>().data(token);
    }

    /**
     * @description 客户端请求刷新token
     * @method  refreshAndGetAuthenticationToken
     * @param  [request]
     * @return com.hx.zjb.security.common.msg.ObjectRestResponse<java.lang.String>
     * @date: 2019/6/18 14:47
     * @author:zhoujinbing
     */
    @RequestMapping(value = "/refresh",method = RequestMethod.GET)
    public ObjectRestResponse<String> refreshAndGetAuthenticationToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshToken = authClientService.refreshToken(token);
        return new ObjectRestResponse<String>().data(refreshToken);
    }

    /**
     * @description 校验token
     * @method  verify
     * @param  [token]
     * @return com.hx.zjb.security.common.msg.ObjectRestResponse<?>
     * @date: 2019/6/18 14:50
     * @author:zhoujinbing
     */
    @RequestMapping(value = "/verify",method = RequestMethod.GET)
    public ObjectRestResponse<?> verify(String token) throws Exception {
        authClientService.verify(token);
        return new ObjectRestResponse<>();
    }











}